import myRouter from "../router/index";
import axios from "axios";
import { apiUrl, hncWebUrl,hncWebAdminUrl } from "@/api/URLConfig";
axios.defaults.timeout = 100000;

axios.interceptors.request.use(
  config => {
    let tokenName = localStorage.getItem("tokenName");
    let tokenValue = localStorage.getItem("tokenValue");
    tokenName && tokenValue && (config.headers[tokenName] = tokenValue);
    return config;
  },
  error => {
    return Promise.error(error);
  }
);

axios.interceptors.response.use(
  response => {
    if (response.data.code === 200) {
      return Promise.resolve(response);
    } else if (response.data.code === 401) {
      myRouter.push({
        path: "/login"
      });
      return Promise.resolve(response);
    } else {
      return Promise.resolve(response);
    }
  },
  // 服务器状态码不是200的情况
  error => {
    return Promise.reject(error);
  }
);

const mesGet = (url, params = {}) => {
  return new Promise((resolve, reject) => {
    axios
      .get(apiUrl + url, {
        params: params
      })
      .then(
        response => {
          resolve(response.data);
        },
        err => {
          reject(err);
        }
      )
      .catch(error => {
        reject(error);
      });
  });
};

const mesPost = (url, params = {}, config) => {
  return new Promise((resolve, reject) => {
    axios
      .post(apiUrl + url, params, config)
      .then(
        response => {
          resolve(response.data);
        },
        err => {
          reject(err);
        }
      )
      .catch(error => {
        reject(error);
      });
  });
};

const hncWebGet = (url, params = {}) => {
  return new Promise((resolve, reject) => {
    axios
      .get(hncWebUrl + url, {
        params: params
      })
      .then(
        response => {
          resolve(response.data);
        },
        err => {
          reject(err);
        }
      )
      .catch(error => {
        reject(error);
      });
  });
};

const hncWebPost = (url, params = {}, config) => {
  return new Promise((resolve, reject) => {
    axios
      .post(hncWebUrl + url, params, config)
      .then(
        response => {
          resolve(response.data);
        },
        err => {
          reject(err);
        }
      )
      .catch(error => {
        reject(error);
      });
  });
};


export default {
  mesGet,
  mesPost,
  hncWebGet,
  hncWebPost
};
